#include <windows.h>
#include <commctrl.h>
#include <stdio.h>
#include <string.h>
int x=12,y=100,fontSize=14,color=0xffff,bgcolor=-1,delay=0,cycles=1;
char fontName[30]="";

void drawText(char *str)
{
    HFONT hfont, hfontold;
    HWND hwnd = GetDesktopWindow();
    HDC hdc = GetWindowDC(hwnd);
    COLORREF otc,obc;
    int obkm=0;
    otc=SetTextColor(hdc, color);
    if(bgcolor==-1)obkm=SetBkMode(hdc,TRANSPARENT);
    obc=SetBkColor(hdc, bgcolor);

    hfont = CreateFont(fontSize,0,0,0,FW_REGULAR,FALSE,FALSE,FALSE,
            DEFAULT_CHARSET,OUT_DEFAULT_PRECIS,CLIP_DEFAULT_PRECIS,
            DEFAULT_QUALITY,DEFAULT_PITCH,fontName
    );
    hfontold = (HFONT)SelectObject(hdc, hfont);
    TextOutA(hdc, x, y, str, strlen(str));
    SelectObject(hdc, hfontold);
    DeleteObject(hfont);
    SetTextColor(hdc, otc);
    SetBkColor(hdc,obc);
    if(obkm!=0)SetBkMode(hdc,obkm);
    ReleaseDC(hwnd,hdc);
}

/*
Usage:
-x <x>
-y <y>
-s <fontsize>
-f <fontname>
-c <color>
-b <background color>
-d <delay ms>
-n <cycles times>
*/
typedef struct{
    const char name;
    void *p;
    const char *s;
}tpara;
tpara paras[]={{'x',&x,"%d"},{'y',&y,"%d"},{'s',&fontSize,"%d"},{'f',&fontName,"%29s"},
    {'c',&color,"%x"},{'b',&bgcolor,"%x"},{'d',&delay,"%d"},{'n',&cycles,"%d"}};
char * nextp(char *s){
    static char *p=NULL;
    char *r=NULL;
    if(s!=NULL)p=s;
    if(p==NULL||*p=='\0')return NULL;
    while(*p==' ' || *p=='\t')p++;
    if(*p=='\0'){
       return NULL;
    }else if(*p=='"'){
        p++;r=p;
        while(*p!='\0'&&*p!='"')p++;
        if(*p!='\0'){*p='\0';p++;}
    }else{
        r=p;
        while(*p!='\0'&& *p!=' ' && *p!='\t')p++;
        if(*p!='\0'){*p='\0';p++;}
    }
    return r;
}
char intro[]="textout [-x <x>] [-y <y>] [-c <color>] [-b <background color>] [-f \"<font name>\"] [-s <font size>] [-d <delay ms>] [-n <cycles>] \"<message>\"";
char eg[]="eg: textout -x 12 -y 100 -c 00ffff -b 0000ff -f \"Segoe UI\" -s 14 -d 0 -n 1 \"Hello!\"";
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    char *t;
    char *msg;
    msg=intro;
    t = nextp(lpCmdLine);
    while (t != NULL) {
        if(*t=='-'){
            t++;
            for(unsigned int i=0;i<(sizeof(paras)/sizeof(paras[0]));i++){
                if(*t==paras[i].name){
                    t=nextp(NULL);
                    if(t==NULL)break;
                    sscanf(t,paras[i].s,paras[i].p);
               }

            }
        }else{
            msg=t;
        }
        t = nextp(NULL);
    }
    if(msg==intro){
            bgcolor=0xff;
            drawText(msg);
            y+=fontSize;
            drawText(eg);
    }else {
        do{
            Sleep(delay);
            drawText(msg);
            cycles--;
        }while(cycles>0);
    }
    return 0;
}
